#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<iostream>
#include<unistd.h>
#include<string.h>
#include<string>

using namespace std;

void Usage(const string &proc)
{
    cout<<"Usage : "<<proc<<"serverip serverport"<<endl;
    exit(1);
}


int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0); 
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        cerr<<"socket error"<<endl;
        return 1;
    }

    int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if(n < 0)
    {
        cerr<<"connect falied.."<<endl;
        return 2;
    }

    string message;

    while(true)
    {
        cout<<"please Enter@";
        getline(cin, message);
        write(sockfd, message.c_str(), message.size());

        char inbuffer[4096];
        int n = read(sockfd, inbuffer, sizeof(inbuffer));
        if(n > 0)
        {
            inbuffer[n] = 0;
            cout<<inbuffer<<endl;
        }
    }

    close(sockfd);
    return 0;
}